package com.yc.yyds.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/upload/*")
public class GetUploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取资源地址
        String uri = request.getRequestURI();
        System.out.println("uri = " + uri);
        //提取文件名
        String filename = uri.replaceAll(".+/upload/(.+)", "$1");
        System.out.println("filename = " + filename);
        //设置返回的内容类型
        String mimeType = request.getServletContext().getMimeType(filename);
        response.setContentType(mimeType);
        //将文件返回给浏览器
        //java.io流
        String path = UploadImageServlet.IMAGE_PATH + filename;
        System.out.println("path = " + path);
        try (FileInputStream fis = new FileInputStream(path)) {
            byte[] buffer = new byte[1024];
            int count;
            ServletOutputStream out = response.getOutputStream();
            while ((count = fis.read(buffer)) > -1) {
                out.write(buffer, 0, count);
            }
        }
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}